""" 
@coding  : utf-8
@Time    : 2023/4/13 15:55
@Author  : Rumou
@File    : 三乐购物系统.py
@Description: 好！重构了
"""
# 平台包含多个商城系统，通用一个平台账号
# 不同系统的商品分类不同，共用一个平台购物车
# 统一在平台购物车结算
# 用户类：(用户名)，密码，用户余额
# 商城类：(商城ID)，商城名
# 商品类：所在商城ID，[(商品ID)，商品名，商品价格]
import json


def load_users():
    """读取用户信息"""
    with open('users.json', 'r', encoding='utf-8') as f:
        users = json.load(f)
    return users


def save_users(users):
    """保存用户信息"""
    with open('users.json', 'w', encoding='utf-8') as f:
        json.dump(users, f, ensure_ascii=False, indent=1)


def load_systems():
    """读取商城系统信息"""
    with open('systems.json', 'r', encoding='utf-8') as f:
        systems = json.load(f)
    return systems


def save_systems(systems):
    """保存商城系统信息"""
    with open('systems.json', 'w', encoding='utf-8') as f:
        json.dump(systems, f, ensure_ascii=False, indent=1)


def load_goods():
    """读取商城系统信息"""
    with open('goods.json', 'r', encoding='utf-8') as f:
        goods = json.load(f)
    return goods


def save_goods(goods):
    """保存商城系统信息"""
    with open('goods.json', 'w', encoding='utf-8') as f:
        json.dump(goods, f, ensure_ascii=False, indent=1)


# 用户类：
class User:
    def __init__(self, name, passwd):
        """用户初始化：用户名，密码"""
        self.name = name
        self.passwd = passwd
        self.init_amount = 1000
        self.shopping_cart = {}

    # 添加用户
    def addUser(self):
        """添加用户：返回布尔值"""
        name = self.name
        passwd = self.passwd
        users_info = load_users()
        if name not in users_info:
            users_info[name] = {"password": passwd,
                                "balance": 1000,
                                "shopping_cart": {}
                                }
            print(f"用户{name}注册成功，初始账户余额为1000元")
            save_users(users_info)
            return True
        else:
            print("用户名已存在，请重新注册")
            return False

    def Login(self):
        name = self.name
        passwd = self.passwd
        users_info = load_users()
        if name in users_info:
            if users_info[name]["password"] == passwd:
                print(f"登录成功，欢迎用户{name}登录")
                return True
            else:
                print("密码错误")
                return False
        else:
            print("用户不存在")
            return False

    # 用户添加商品到购物车
    def addGoodsToCart(self, sys_id, goods_id, goods_count):
        """添加商品到购物车：传入所在商城ID，商品ID，商品数量，返回布尔值"""
        user_name = self.name
        goods_info = load_goods()
        users_info = load_users()
        if goods_id in goods_info[sys_id]:  # 商品ID存在购物系统
            if sys_id not in users_info[user_name]["shopping_cart"]:  # 购物车无该商城ID分类
                users_info[user_name]["shopping_cart"][sys_id] = {}
            if goods_id not in users_info[user_name]["shopping_cart"][sys_id]:  # 购物车无该物品ID
                users_info[user_name]["shopping_cart"][sys_id][goods_id] = 0
            if goods_count.isdigit():
                users_info[user_name]["shopping_cart"][sys_id][goods_id] += int(goods_count)
                print(f"商品{goods_info[sys_id][goods_id]['name']}"
                      f"*{goods_count}成功添加到购物车")
                save_users(users_info)
                return True
            else:
                print("商品数量输入有误")
                return False
        else:
            print("商品不存在")
            return False

    # 用户查看购物车
    def showCart(self):
        """查看购物车"""
        users_info = load_users()
        sys_info = load_systems()
        goods_info = load_goods()
        user_name = self.name
        if users_info[user_name]["shopping_cart"] == {}:
            print("购物车为空")
            return
        else:
            print("商城名\t\t商品名\t商品单价\t商品数量\t小计")
            total = 0
            for sys_id in users_info[user_name]["shopping_cart"]:
                for good_id in users_info[user_name]["shopping_cart"][sys_id]:
                    print(f"{sys_info[sys_id]['sys_name']}", end="\t")  # 商城名
                    print(f"{goods_info[sys_id][good_id]['name']}", end='\t\t')  # 商品名
                    print(f"{goods_info[sys_id][good_id]['price']}", end="\t\t")  # 商品单价
                    print(f"{users_info[user_name]['shopping_cart'][sys_id][good_id]}", end='\t\t')  # 商品数量
                    print(
                        f"{goods_info[sys_id][good_id]['price'] * users_info[user_name]['shopping_cart'][sys_id][good_id]}")  # 小计
                    total += goods_info[sys_id][good_id]['price'] * users_info[user_name]['shopping_cart'][sys_id][
                        good_id]
            print(f"总计：\t\t\t\t\t\t\t\t{total}")

    def getCheckoutCart(self):
        """获取用户购物车商品总价格，返回一个int"""
        users_info = load_users()
        load_systems()
        goods_info = load_goods()
        user_name = self.name
        if users_info[user_name]["shopping_cart"] == {}:
            print("购物车为空，不能结算")
        else:
            total = 0
            for sys_id in users_info[user_name]["shopping_cart"]:
                for good_id in users_info[user_name]["shopping_cart"][sys_id]:
                    total += goods_info[sys_id][good_id]['price'] * users_info[user_name]['shopping_cart'][sys_id][
                        good_id]
            return total


# 商城系统类
class ShoppingSystem:
    def __init__(self, sys_id, sys_name):
        """商城类初始化：系统ID，系统名"""
        self.sys_id = sys_id
        self.sys_name = sys_name

    def addSys(self):
        """添加系统：返回布尔值"""
        sys_id = self.sys_id
        sys_name = self.sys_name
        sys_info = load_systems()
        goods_info = load_goods()
        if sys_id not in sys_info:
            sys_info[sys_id] = {"sys_name": sys_name}
            goods_info[sys_id] = {}
            save_goods(goods_info)
            save_systems(sys_info)
            print(f"{sys_name}添加成功")
            return True
        else:
            print("商城系统ID已存在，请重新添加")
            return False

    def showAllGoods(self):
        sys_id = self.sys_id
        goods_info = load_goods()
        print("商品ID\t商品名\t商品单价")
        for goods_id in goods_info[sys_id]:
            print(
                f"{goods_id}\t\t{goods_info[sys_id][goods_id]['name']}\t\t"
                f"{goods_info[sys_id][goods_id]['price']}")


# 商品类
class Goods:
    def __init__(self, sys_id, goods_id, goods_name, goods_price):
        """商品类初始化：所在商城ID，商品ID，商品名，商品价格"""
        self.sys_id = sys_id
        self.goods_id = goods_id
        self.goods_name = goods_name
        self.goods_price = goods_price

    def addGoods(self):
        """添加商品：返回布尔值"""
        goods_info = load_goods()
        sys_info = load_systems()
        sys_id = self.sys_id
        goods_id = self.goods_id
        goods_name = self.goods_name
        goods_price = int(self.goods_price)
        if sys_id not in sys_info:
            print("商城ID不存在")
        else:
            if goods_id not in goods_info[sys_id]:  # 商品ID不在该商品中
                goods_info[sys_id][goods_id] = {"name": goods_name, "price": goods_price}
                save_goods(goods_info)
                print(f"成功在{sys_info[sys_id]['sys_name']}中添加商品{goods_id}.{goods_name}")
            else:  # 商品ID在该商城中
                print(f"{sys_id}.{sys_info[sys_id]['sys_name']}中已存在{goods_id}.{goods_name}商品")


# 展示所有商城信息
def showAllSys():
    sys_info = load_systems()
    for sys_id in sys_info:
        print(f"{sys_id}.{sys_info[sys_id]['sys_name']}")


# 判断用户是否存在
def user_exist(name):
    users_info = load_users()
    if name in users_info:
        return True
    else:
        return False


# 用户充值
def recharge(name, count, choice):
    users_info = load_users()
    if choice == 1:  # 充值
        if count.isdigit():
            count = int(count)
            if user_exist(name):
                users_info[name]["balance"] += count
                print(f"充值成功！用户{name}的余额为{users_info[name]['balance']}")
                save_users(users_info)
            else:
                print("不存在该用户")
        else:
            print("充值金额有误")
    elif choice == 2:
        if count.isdigit():
            count = int(count)
            if user_exist(name):
                users_info[name]["balance"] -= count
                if users_info[name]["balance"] < 0:
                    users_info[name]["balance"] = 0
                    print(f"扣除后用户{name}余额为负数，已默认清空")
                else:
                    print(f"扣除成功！用户{name}的余额为{users_info[name]['balance']}")
                save_users(users_info)
            else:
                print("不存在该用户")
        else:
            print("充值金额有误")


def main():
    print("欢迎来到三乐购物系统".center(36, "-"))
    while True:
        print("-" * 30)
        login_choice = input("1.登录\n2.注册\n3.退出系统\n请输入你的选择：")
        if login_choice == "1":
            input_name = input("请输入用户名：")
            input_passwd = input("请输入密码：")
            input_user = User(input_name, input_passwd)  # 实例化input_user对象
            if input_user.Login():  # 用户登录成功
                while True:
                    print("欢迎进入商城".center(30, "-"))
                    print("目前已有商城如下：")
                    showAllSys()  # 显示所有商城系统
                    sys_info = load_systems()
                    print(f"{len(sys_info) + 1}.管理员系统")
                    print(f"{len(sys_info) + 2}.退出登录")
                    system_choice = input("请输入你的选择：")
                    if system_choice in sys_info:  # 用户商城选择在商城ID列表中
                        current_system = ShoppingSystem(system_choice, sys_info[system_choice])  # 初始化current_system对象实例
                        while True:
                            print("-" * 36)
                            print("1.查看商品\n2.添加购物车\n3.查看购物车\n4.结算购物车\n5.退出当前商城")
                            user_choice = input("请输入你的选择：")
                            if user_choice == "1":  # 用户查看当前商城商品
                                current_system.showAllGoods()
                            elif user_choice == "2":  # 用户添加购物车
                                goods_id_choice = input("请输入要购买的商品ID:")
                                goods_count_choice = input("请输入要购买的数量：")
                                input_user.addGoodsToCart(system_choice, goods_id_choice, goods_count_choice)
                            elif user_choice == "3":  # 用户查看购物车
                                input_user.showCart()
                            elif user_choice == "4":  # 用户结算购物车
                                total = input_user.getCheckoutCart()
                                check_choice = input(f"购物车总计{total}元，是否继续结算(y/n)：")
                                if check_choice == "y":  # 用户确认结算购物车
                                    user_info = load_users()
                                    balance = user_info[input_user.name]["balance"]
                                    if balance >= total:  # 余额 >=总计
                                        balance = user_info[input_user.name]["balance"] - total
                                        user_info[input_user.name]["balance"] = balance
                                        user_info[input_user.name]['shopping_cart'].clear()
                                        save_users(user_info)
                                        print(f"结算成功，账户余额剩余{balance}元")
                                    else:  # 余额 < 总计
                                        print(f"结算失败，账户余额不足。当前账户余额为{balance}元")
                                elif check_choice == "n":
                                    pass
                                else:
                                    print("输入有误")
                            elif user_choice == "5":  # 用户退出当前商城
                                print(f"退出{sys_info[system_choice]['sys_name']}".center(30, "-"))
                                break
                            else:
                                print("输入有误")
                    elif system_choice == str(len(sys_info) + 1):  # 用户选择管理员系统
                        if input_user.name == "admin":  # 用户名为admin
                            while True:
                                print("管理员系统".center(30, "-"))
                                print("1.添加商城\n2.添加商品\n3.账户余额管理\n4.退出管理员系统")
                                admin_choice = input("请输入你的选择：")
                                if admin_choice == "1":
                                    print("平台中已有系统如下：")
                                    showAllSys()
                                    input_sys_id = input("请输入要添加的商城ID：")
                                    input_sys_name = input("请输入要添加的商城名：")
                                    system_admin_input = ShoppingSystem(input_sys_id, input_sys_name)
                                    system_admin_input.addSys()
                                elif admin_choice == "2":
                                    system_id_admin_input = input("请选择商城ID：")
                                    goods_id_admin_input = input("请输入要添加的商品ID：")
                                    goods_name_admin_input = input("请输入要添加的商品名：")
                                    goods_price_admin_input = input("请输入要添加的商品单价：")
                                    goods_admin_input = Goods(system_id_admin_input, goods_id_admin_input,
                                                              goods_name_admin_input, goods_price_admin_input)
                                    goods_admin_input.addGoods()
                                elif admin_choice == "3":
                                    user_admin_charge_choice = input("充值/扣除？(1/2)")
                                    if user_admin_charge_choice == "1":
                                        user_admin_input = input("请输入要充值的用户名：")
                                        count_admin_input = input("请输入金额：")
                                        recharge(user_admin_input, count_admin_input, 1)
                                    elif user_admin_charge_choice == "2":
                                        user_admin_input = input("请输入要扣除的用户名：")
                                        count_admin_input = input("请输入金额：")
                                        recharge(user_admin_input, count_admin_input, 2)
                                    else:
                                        print("输入有误")
                                elif admin_choice == "4":
                                    print("退出管理员系统")
                                    break
                                else:
                                    print("输入有误")
                        else:  # 无权限进入管理员系统
                            print("没有权限")
                    elif system_choice == str(len(sys_info) + 2):  # 用户选择退出登录
                        print("退出登录".center(30, "-"))
                        break
                    else:
                        print("输入有误")
                        continue
            else:  # 登录失败
                continue
        if login_choice == "2":
            input_name = input("请输入用户名：")
            input_passwd = input("请输入密码：")
            input_user = User(input_name, input_passwd)
            input_user.addUser()
        if login_choice == "3":
            print("再见")
            break


# 执行主程序
if __name__ == "__main__":
    main()
